/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.worldscale.xp.wslib.im.jabber.impl;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import net.worldscale.xp.wslib.im.jabber.JabberClient;
import net.worldscale.xp.wslib.wsxml.WsXML;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author Kun
 */
final class ImplJabberDispatcher implements JabberClient.Dispatcher {

    public static interface StanzaListener {

        void onStanza(Element stanza);
    }
    private final OutputStream mOS;
    private StanzaListener mListener;

    public ImplJabberDispatcher(OutputStream os) {
        mOS = os;
    }

    public StanzaListener getListener() {
        return mListener;
    }

    public void setListener(StanzaListener l) {
        this.mListener = l;
    }

    private void internal_sendBytes(byte[] buf, int off, int len) throws IOException {
        synchronized (this) {
            mOS.write(buf, off, len);
            mOS.flush();
        }
        final StanzaListener l = this.mListener;
        if (l != null) {
            final ByteArrayInputStream bais = new ByteArrayInputStream(buf, off, len);
            final Document doc = WsXML.getInstance().createDOM(bais, "xmpp");
            final Element stanza = doc.getDocumentElement();
            l.onStanza(stanza);
        }
    }

    public void closeStream() throws IOException {
        String str = ("</stream:stream>");
        this.send(str);
    }

    public void openStream(String host) throws IOException {
        String str = ("<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='" + host + "' version='1.0'>");
        this.send(str);
    }

    public void send(byte[] buf) throws IOException {
        this.internal_sendBytes(buf, 0, buf.length);
    }

    public void send(byte[] buf, int off, int len) throws IOException {
        this.internal_sendBytes(buf, off, len);
    }

    public void send(String str) throws IOException {
        byte[] buf = str.getBytes("utf-8");
        this.internal_sendBytes(buf, 0, buf.length);
    }
}
